package com.swanclouds.redfish.sessions;

import com.google.common.base.Preconditions;
import com.swanclouds.api.session.SessionService;
import com.swanclouds.core.transport.ClientConstants;
import com.swanclouds.core.transport.HttpResponse;
import com.swanclouds.model.common.ActionResponse;
import com.swanclouds.model.common.redfish.CollectionResource;
import com.swanclouds.model.identity.AuthStore;
import com.swanclouds.model.identity.Token;
import com.swanclouds.model.sessions.Session;
import com.swanclouds.redfish.common.Auth;
import com.swanclouds.redfish.common.redfish.CollectionResourceModel;
import com.swanclouds.redfish.identity.RedfishAuth;
import com.swanclouds.redfish.identity.RedfishToken;
import com.swanclouds.redfish.internal.BaseRedfishService;
import com.swanclouds.redfish.internal.OSClientSession;
import com.swanclouds.redfish.sessions.domain.SessionConcrete;

public class SessionServiceImpl extends BaseRedfishService implements SessionService {


    @Override
    public Session get() {
        return get(SessionConcrete.class,uri(ClientConstants.PATH_SESSIONSERVICE)).execute();
    }

    @Override
    public Token create(AuthStore auth) {
        Token token = new RedfishToken();
        HttpResponse response = this.post(HttpResponse.class, uri(ClientConstants.SESSIONSERVICE_SESSIONS)).entity(auth).executeWithResponse();
        if (response.getStatus() == 201) {
            token.setETag(response.headers().get(ClientConstants.HEADER_ETAG));
            token.setId(response.headers().get(ClientConstants.HEADER_X_AUTH_TOKEN));
            ((RedfishToken) token).setEndpoint(super.getXRedfishEndpoint());
            ((RedfishToken) token).setLocation(response.header(ClientConstants.HEADER_LOCATION));
            ((RedfishToken) token).setCredentials(new RedfishAuth(auth.getUsername(),auth.getPassword(), Auth.Type.TOKEN));
            OSClientSession.OSClientSessionV1.createSession(token, super.getProvider(), super.getXRedfishConfig());
        }
        return token;
    }

    /**
     * 查询会话集合信息
     * @return this
     */
    @Override
    public CollectionResource getSessions() {
        return get(CollectionResourceModel.class, uri(ClientConstants.SESSIONSERVICE_SESSIONS)).execute();
    }

    /**
     * 查询指定会话资源信息
     *
     * @param sessionId 会话ID
     * @return this
     */
    @Override
    public Session getSession(String sessionId) {
        Preconditions.checkNotNull(sessionId, "Session ID is null");
        return get(SessionConcrete.class, uri(ClientConstants.SESSIONSERVICE_SESSIONS_ID, sessionId)).execute();
    }

    /**
     * 删除指定会话资源信息
     *
     * @param sessionId 会话ID
     * @return this response
     */
    @Override
    public ActionResponse delete(String sessionId) {
        Preconditions.checkNotNull(sessionId, "Session ID is null");
        return deleteWithResponse(uri(ClientConstants.SESSIONSERVICE_SESSIONS_ID, sessionId)).execute();
    }
}
